package com.example.tccdemo.config;

import com.mysql.cj.jdbc.MysqlDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @author caryguan
 * @version V1.0
 * @Package com.example.tccdemo.config
 * @date 2020/10/15 19:01
 */

@Configuration
@MapperScan(value = "com.example.tccdemo.db163.dao", sqlSessionFactoryRef = "factory163")
public class ConfigDB163 {

    @Bean("db163")
    public DataSource db163() {
        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setUser("imooc");
        dataSource.setPassword("Imooc@123456");
        dataSource.setUrl("jdbc:mysql://192.168.124.163:3306/xa-163");

        return dataSource;
    }

    @Bean("factory163")
    public SqlSessionFactoryBean factoryBean(@Qualifier("db163") DataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);

        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resourceResolver.getResources("mybatis/db163/*.xml"));

        return sqlSessionFactoryBean;
    }

    //配置事务管理器,因为我们这个不是X基于A的协议所以可以配两个事务管理器
    @Bean("tm163")
    public PlatformTransactionManager transactionManager(@Qualifier("db163") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}